# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging,sys

logger = logging.getLogger()


def adstr2addr(adstr):
    a = adstr.split(':')
    if len(a) == 1:
        if a[0].isdigit():
            if int(a[0]) < 8000:
                logger.warning("Error for port %s, it has to be greater 8000, use default value",a[0])
                addr = None
            else:
                addr = (None,a[0])
        else:
            addr = (a[0],None)
    elif len(a) == 2:
        if a[1].isdigit():
            if int(a[1]) < 8000:
                a[1] = None
                logger.warning("Error for port %s, it has to be greater 8000, use default value",a[1])
        else:
            a[1] = None
        addr = (a[0],a[1])
    else:
        addr = None
    return addr


def addr2host(defaddr,addr=None):
    """
    defaddr=('localhost','9000')
    """
    if addr :
       host,port = addr
    else:
       host,port = None,None
    if host is None:
       host = defaddr[0]
    if port:
       port = int(port)
    else:
       port = int(defaddr[1])
    return host,port


def log2console():
    logger = logging.getLogger()
    hdlr = logging.StreamHandler() # Console
    formatter = logging.Formatter('%(module)s - %(asctime)s %(levelname)s %(message)s')
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
